package com.alm.token.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alm.token.ConStant;
import com.alm.token.GlideApp;
import com.alm.token.MyApp;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.base.BaseAdapter;
import com.alm.token.common.RefreshLoadMoreManager;
import com.alm.token.ui.data.bean.MyTeamData;
import com.alm.token.ui.data.bean.UserData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.MineView;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.EmptyUtils;
import com.alm.token.utils.LanguageUtils;
import com.alm.token.utils.LogUtil;
import com.alm.token.widget.CustomFlagLayout;
import com.chad.library.adapter.base.BaseViewHolder;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class GroupActivity extends BaseActivity implements MineView<UserData> {
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.tv_nownodename)
    TextView tvNownodename;
    @BindView(R.id.tv_yeji)
    TextView tvYeJi;
    @BindView(R.id.tv_shouyigaodu)
    TextView tvShouYiGgoDu;
    @BindView(R.id.tv_yeji1)
    TextView tvYeJi1;
    @BindView(R.id.tv_shouyigaodu1)
    TextView tvShouYiGgoDu1;
    @BindView(R.id.tv_yeji2)
    TextView tvYeJi2;
    @BindView(R.id.tv_shouyigaodu2)
    TextView tvShouYiGgoDu2;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.tv_clickreload)
    TextView tvClickreload;
    @BindView(R.id.ly_nodenamebody)
    RelativeLayout lyNodenameBody;


    @BindView(R.id.ly_serchbody)
    LinearLayout lySearchBody;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.recycler_searchview)
    RecyclerView recyclerSearchView;

    @BindView(R.id.nodatashow_body)
    RelativeLayout nodatashowBody;
    @BindView(R.id.centerItem)
    TextView centerItem;
    private RefreshLoadMoreManager<MyTeamData.DataBean.TeamBean> manager;
    private List<MyTeamData.DataBean.TeamBean> dataBeans = new ArrayList<>();

    private RefreshLoadMoreManager<MyTeamData.DataBean.TeamBean> managerSearch;
    private List<MyTeamData.DataBean.TeamBean> dataBeansSearch = new ArrayList<>();

    @Override
    protected MyPreenter initPreenter() {
        return new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_group;
    }

    @Override
    protected void initVariables() {

    }

    @Override
    protected void initViews() {
        new ActionBarHelper(this).setTitle(getString(R.string.title_hint_item4));
        swipeRefreshLayout.setVisibility(View.GONE);
        lySearchBody.setVisibility(View.GONE);
        initManager();
    }

    private void initManager() {
        GroupAdapter adapter = new GroupAdapter(this);
        manager = new RefreshLoadMoreManager.Builder(this)
                .setAdapter(adapter)
                .setRecyclerView(recyclerView)
                .setSwipeRefreshLayout(swipeRefreshLayout)
                .setOnRefreshListener(new RefreshLoadMoreManager.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
//                        showToast("onRefresh");
                        swipeRefreshLayout.setRefreshing(false);
                        loadData();
                    }
                })
                .build();


        GroupAdapter adapter1 = new GroupAdapter(this);
        managerSearch = new RefreshLoadMoreManager.Builder(this)
                .setAdapter(adapter1)
                .setRecyclerView(recyclerSearchView)
                .build();

        etSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 输入的内容变化的监听
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // 输入前的监听
            }

            @Override
            public void afterTextChanged(Editable s) {
                // 输入后的监听
                if (TextUtils.isEmpty(etSearch.getText().toString())) {
                    recyclerSearchView.setVisibility(View.GONE);
                    if (EmptyUtils.isNotEmpty(dataBeans))
                        swipeRefreshLayout.setVisibility(View.VISIBLE);
                } else {
                    recyclerSearchView.setVisibility(View.VISIBLE);
                    swipeRefreshLayout.setVisibility(View.GONE);

                    dataBeansSearch.clear();

                    for (int i = 0; i < dataBeans.size(); i++) {
                        MyTeamData.DataBean.TeamBean.LohasUserBean lohasUserBean = dataBeans.get(i).getLohasUser();
                        if (EmptyUtils.isNotEmpty(lohasUserBean) && (
                                lohasUserBean.getPhone().contains(etSearch.getText().toString()) ||
                                        lohasUserBean.getLoginname().contains(etSearch.getText().toString())
                        )) {
                            dataBeansSearch.add(dataBeans.get(i));
                        }

                    }

                    managerSearch.setData(dataBeansSearch);

                    //UiUtil.showToast(FundArealistActivity.this, et_search.getText().toString());
                }
            }
        });

        recyclerView.setNestedScrollingEnabled(false);
        recyclerSearchView.setNestedScrollingEnabled(false);
    }

    @Override
    protected void loadData() {
        ShowProgress();
        preenter.getMyTeamData();
//        manager.setData(getTestData());
    }


    @Override
    public void onClick(View v) {

    }

    @Override
    public void getData(UserData userData) {

    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        } else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(this,PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            finish();
            showToSetPaypswDialog();
        }else if (staue == 666) {
            showToUpdata();
        }
    }

    @Override
    public void onError(String error) {

        showToast(getString(R.string.common_loaderrritry));
    }

    @Override
    public void ShowProgress() {
        showWaitDialog();
    }

    @Override
    public void hideProgress() {
        hideWaitDialog();
    }

    @Override
    public void getMyTeamData(MyTeamData myTeamData) {

        if (myTeamData.getStatus() == 0 && myTeamData.getData() != null) {
            MyApp.setMyTeamDataBean(myTeamData.getData());
            MyTeamData.DataBean dataBean = myTeamData.getData();
            centerItem.setText(getString(R.string.title_hint_item4) + "(" + dataBean.getNum() + ")");
//            tvNownodenumber.setText(dataBean.getNum() + "");
            MyTeamData.DataBean.LevelBean levelBean = dataBean.getLevel();

            String lianghuayeji = CommonUtil.saveToPoint2WithNo(dataBean.getQuantification_yj());
            String sktyeji = CommonUtil.saveToPoint2WithNo(dataBean.getSkt_yj());
            String zhongchouyeji = CommonUtil.saveToPoint2WithNo(dataBean.getCrowd_yj());
            tvYeJi.setText(zhongchouyeji);
            tvYeJi1.setText("$" + sktyeji);
            tvYeJi2.setText("$" + lianghuayeji);
            String lianghuafloor = "" + dataBean.getQuantification_floor();
            String sktfloor = "" + dataBean.getSkt_floor();
            String zhongchoufloor = "" + dataBean.getCfd_floor();
            tvShouYiGgoDu.setText(zhongchoufloor);
            tvShouYiGgoDu1.setText(sktfloor);
            tvShouYiGgoDu2.setText(lianghuafloor);

            if (levelBean != null) {
                tvNownodename.setText(TextUtils.isEmpty(levelBean.getCfdSubProName()) ? getString(R.string.mine_hint_empty1) : levelBean.getCfdSubProName());
                if (tvNownodename.getText().toString().indexOf(getString(R.string.mine_hint_empty1)) != -1) {
                    lyNodenameBody.setVisibility(View.GONE);
                }
            } else {
                lyNodenameBody.setVisibility(View.GONE);
            }
            if (dataBean.getTeam() != null) {
                dataBeans = dataBean.getTeam();
            }

            if (dataBeans != null) {
                for (int i = 0; i < dataBeans.size(); i++) {
                    dataBeans.get(i).setLayoutId(GroupAdapter.LAYOUT_ID);
                }
                manager.setData(dataBeans);
            }
            if (dataBeans.size() == 0) {
                swipeRefreshLayout.setVisibility(View.GONE);
                lySearchBody.setVisibility(View.GONE);
                nodatashowBody.setVisibility(View.VISIBLE);
            } else {
                swipeRefreshLayout.setVisibility(View.VISIBLE);
                lySearchBody.setVisibility(View.VISIBLE);
                nodatashowBody.setVisibility(View.GONE);
            }
        } else showToast(myTeamData.getMsg());
    }

    @OnClick(R.id.tv_clickreload)
    public void onViewClicked() {
        loadData();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    public class GroupAdapter extends BaseAdapter<MyTeamData.DataBean.TeamBean> {

        public static final int LAYOUT_ID = R.layout.item_group;

        public GroupAdapter(@NonNull Context context) {
            super(context);
        }

        @Override
        protected void convert(BaseViewHolder helper, MyTeamData.DataBean.TeamBean item, int itemType) {

            MyTeamData.DataBean.TeamBean.LohasUserBean lohasUserBean = item.getLohasUser();
            ImageView icon = helper.getView(R.id.icon);
            String url = "https://tvax3.sinaimg.cn/crop.0.0.996.996.180/56303b98ly8fndrnuk3z6j20ro0rodjg.jpg";
            GlideApp.with(GroupActivity.this).load(url).circleCrop().into(icon);

            if (lohasUserBean != null) {
                String mail = lohasUserBean.getEmail();
                if (mail != null) {
                    String[] split =mail.split("@");
                    mail=split[0].length() > 4 ? split[0].substring(0, 2) + "****" + split[0].substring(split[0].length() - 2, split[0].length()) + "@" + split[1] : mail;
                }

                helper.setText(R.id.mobile, lohasUserBean.getLoginname() + "    " + (EmptyUtils.isNotEmpty(lohasUserBean.getCountry()) ? lohasUserBean.getCountry() : "")
                        + (EmptyUtils.isNotEmpty(mail) ? mail : ""));
                helper.setText(R.id.date, CommonUtil.getDateTimeFromMillisecond(item.getCreateTime()).split(" ")[0]);


//                if (TextUtils.isEmpty(item.getNodeName()) || item.getNodeName().indexOf(getString(R.string.mine_hint_empty1)) != -1) {
//                    helper.setVisible(R.id.tv_nodename, false);
//                } else {
//                    helper.setVisible(R.id.tv_nodename, true);
//                    helper.setText(R.id.tv_nodename, item.getNodeName());
//                }
            }
            helper.setVisible(R.id.tv_nodename, false);
            helper.setVisible(R.id.tv_lianghuaname, false);
            helper.setVisible(R.id.tv_zongchouxingjiname, false);

            CustomFlagLayout lyUserLabelbody = helper.getView(R.id.ly_userLabelbody);
            lyUserLabelbody.removeAllViews();
            if (EmptyUtils.isNotEmpty(item) && EmptyUtils.isNotEmpty(item.getUserLabel())) {
                Map<String, String> userLabel = item.getUserLabel();

                for (String key : userLabel.keySet()) {

                    LogUtil.e("io");
                    TextView textView = new TextView(context);
                    textView.setText("   " + key + "   ");
                    textView.setTextSize(CommonUtil.dip2px(context, 5));
                    LinearLayout.LayoutParams textParamsRoot = new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.WRAP_CONTENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT);
//                    textParamsRoot.height = CommonUtil.dip2px(context, 30);
                    textParamsRoot.gravity = Gravity.CENTER;
                    textView.setLayoutParams(textParamsRoot);
                    textView.setGravity(Gravity.CENTER);
                    int padding = CommonUtil.dip2px(context, 5);
                    textView.setPadding(0,padding,0,padding);
                    GradientDrawable drawable = (GradientDrawable) context.getResources().getDrawable(R.drawable.shape_me_userflag);
                    drawable.setColor(Color.parseColor(userLabel.get(key)));
                    textView.setBackgroundDrawable(drawable);
                    lyUserLabelbody.addView(textView);
                }


            } else {
                LogUtil.e("2222");
            }


//            int ll1 = item.getMaxLevel();
//            if (ll1 == 0) {
//                helper.setVisible(R.id.tv_lianghuaname, false);
//            } else {
//                helper.setVisible(R.id.tv_lianghuaname, true);
//                helper.setText(R.id.tv_lianghuaname, getString(R.string.mine_hint_group1, "" + ll1));
//            }
//
//            if (TextUtils.isEmpty(item.getCfdLevelName())) {
//                helper.setVisible(R.id.tv_zongchouxingjiname, false);
//            } else {
//                helper.setVisible(R.id.tv_zongchouxingjiname, true);
//                helper.setText(R.id.tv_zongchouxingjiname, getString(R.string.mine_hint_group2, "" + item.getCfdLevelName()));
//            }
        }

    }
}
